// pages/comment/comment.js - 评论详情页
const { api } = require('../../utils/api')
const { formatRelativeTime } = require('../../utils/util')
const app = getApp()

Page({
  data: {
    postId: null,
    postInfo: {
      title: '',
      commentCount: 0
    },
    comments: [],
    commentInput: '',
    replyingTo: null, // { commentId, username }
    page: 1,
    pageSize: 20,
    hasMore: true,
    loading: false
  },

  onLoad(options) {
    if (options.postId) {
      this.setData({ postId: options.postId })
      this.loadComments(true)
    }
    // 获取动态标题信息
    if (options.title) {
      this.setData({
        'postInfo.title': decodeURIComponent(options.title)
      })
    }
    if (options.commentCount) {
      this.setData({
        'postInfo.commentCount': parseInt(options.commentCount)
      })
    }
  },

  // 加载评论列表
  loadComments(refresh = false) {
    if (this.data.loading) return
    if (!refresh && !this.data.hasMore) return

    this.setData({ loading: true })

    const page = refresh ? 1 : this.data.page
    
    api.community.getPostComments({
      postId: this.data.postId,
      page,
      pageSize: this.data.pageSize
    }).then(data => {
      const formattedComments = data.list.map(comment => ({
        ...comment,
        time: formatRelativeTime(comment.createTime)
      }))

      this.setData({
        comments: refresh ? formattedComments : [...this.data.comments, ...formattedComments],
        page: page + 1,
        hasMore: formattedComments.length === this.data.pageSize,
        loading: false
      })
    }).catch(err => {
      console.error('加载评论失败:', err)
      wx.showToast({ title: '加载失败', icon: 'none' })
      this.setData({ loading: false })
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadComments(true)
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  // 上拉加载更多
  onReachBottom() {
    this.loadComments(false)
  },

  // 输入评论
  onCommentInput(e) {
    this.setData({ commentInput: e.detail.value })
  },

  // 点击回复
  onReply(e) {
    const { id, username } = e.currentTarget.dataset
    this.setData({
      replyingTo: { commentId: id, username },
      commentInput: `@${username} `
    })
  },

  // 取消回复
  cancelReply() {
    this.setData({
      replyingTo: null,
      commentInput: ''
    })
  },

  // 提交评论
  submitComment() {
    const { commentInput, postId, replyingTo } = this.data

    if (!commentInput.trim()) {
      wx.showToast({ title: '请输入评论内容', icon: 'none' })
      return
    }

    const userInfo = app.globalData.userInfo
    if (!userInfo) {
      wx.showToast({ title: '请先登录', icon: 'none' })
      return
    }

    wx.showLoading({ title: '发送中...' })

    api.community.addPostComment({
      postId,
      content: commentInput.trim(),
      parentId: replyingTo ? replyingTo.commentId : null
    }).then(() => {
      wx.hideLoading()
      wx.showToast({ title: '评论成功', icon: 'success' })
      
      // 清空输入框和回复状态
      this.setData({
        commentInput: '',
        replyingTo: null
      })
      
      // 刷新评论列表
      this.loadComments(true)
      
      // 更新评论数
      this.setData({
        'postInfo.commentCount': this.data.postInfo.commentCount + 1
      })
    }).catch(err => {
      wx.hideLoading()
      console.error('评论失败:', err)
      wx.showToast({ title: '评论失败，请重试', icon: 'none' })
    })
  },

  // 点赞评论
  toggleCommentLike(e) {
    const { index, id } = e.currentTarget.dataset
    const comment = this.data.comments[index]
    
    // 乐观更新
    this.setData({
      [`comments[${index}].isLiked`]: !comment.isLiked,
      [`comments[${index}].likeCount`]: comment.isLiked ? 
        comment.likeCount - 1 : 
        comment.likeCount + 1
    })

    // 调用API（占位）
    const apiCall = comment.isLiked ? 
      api.community.unlikeComment : 
      api.community.likeComment

    apiCall({ commentId: id }).catch(err => {
      console.error('操作失败:', err)
      // 回滚
      this.setData({
        [`comments[${index}].isLiked`]: comment.isLiked,
        [`comments[${index}].likeCount`]: comment.likeCount
      })
    })
  },

  // 删除评论
  deleteComment(e) {
    const { index, id } = e.currentTarget.dataset
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条评论吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' })
          
          api.community.deleteComment({ commentId: id }).then(() => {
            wx.hideLoading()
            wx.showToast({ title: '删除成功', icon: 'success' })
            
            // 从列表中移除
            const comments = [...this.data.comments]
            comments.splice(index, 1)
            this.setData({
              comments,
              'postInfo.commentCount': this.data.postInfo.commentCount - 1
            })
          }).catch(err => {
            wx.hideLoading()
            console.error('删除失败:', err)
            wx.showToast({ title: '删除失败', icon: 'none' })
          })
        }
      }
    })
  }
})
